package com.wj.gulimall.product.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wj.common.utils.PageUtils;
import com.wj.common.utils.Query;
import com.wj.common.utils.R;
import com.wj.gulimall.product.dao.SkuInfoDao;
import com.wj.gulimall.product.entity.SkuImagesEntity;
import com.wj.gulimall.product.entity.SkuInfoEntity;
import com.wj.gulimall.product.entity.SpuInfoDescEntity;
import com.wj.gulimall.product.feign.SeckillFeignService;
import com.wj.gulimall.product.service.*;
import com.wj.gulimall.product.vo.SeckillInfoVo;
import com.wj.gulimall.product.vo.SkuItemSaleAttrVo;
import com.wj.gulimall.product.vo.SkuItemVo;
import com.wj.gulimall.product.vo.SpuItemAttrGroupVo;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;

@RequiredArgsConstructor
@Service("skuInfoService")
public class SkuInfoServiceImpl extends ServiceImpl<SkuInfoDao, SkuInfoEntity> implements SkuInfoService {

    final SkuInfoDao skuInfoDao;

    final SkuImagesService imagesService;

    final SpuInfoDescService spuInfoDescService;

    final AttrGroupService attrGroupService;

    final SkuSaleAttrValueService skuSaleAttrValueService;

    final ThreadPoolExecutor executor;

    final SeckillFeignService seckillFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SkuInfoEntity> page = this.page(
                new Query<SkuInfoEntity>().getPage(params),
                new QueryWrapper<SkuInfoEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void saveSkuInfo(SkuInfoEntity skuInfoEntity) {
        this.save(skuInfoEntity);
    }

    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        QueryWrapper<SkuInfoEntity> wrapper = new QueryWrapper<>();

        String key = (String) params.get("key");
        if (StringUtils.isNotBlank(key)) {
            wrapper.and(w -> {
                w.eq("sku_id", key).or().like("sku_name", key);
            });
        }

        String brandId = (String) params.get("brandId");
        wrapper.eq(StringUtils.isNotBlank(brandId) && !"0".equals(brandId), "brand_id", brandId);

        String catalogId = (String) params.get("catelogId");
        wrapper.eq(StringUtils.isNotBlank(catalogId) && !"0".equals(catalogId), "catalog_id", catalogId);

        String min = (String) params.get("min");
        wrapper.ge(StringUtils.isNotBlank(min) && compareZero(min), "price", min);

        String max = (String) params.get("max");
        wrapper.ge(StringUtils.isNotBlank(max) && compareZero(max), "price", max);

        IPage<SkuInfoEntity> page = this.page(
                new Query<SkuInfoEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    @Override
    public String getSkuName(Long skuId) {
        SkuInfoEntity skuInfoEntity = skuInfoDao.selectById(skuId);
        return skuInfoEntity.getSkuName();
    }

    @Override
    public List<SkuInfoEntity> getSkusBySpuId(Long spuId) {
        return this.list(new QueryWrapper<SkuInfoEntity>().eq("spu_id", spuId));
    }

    private boolean compareZero(String value) {
        try {
            BigDecimal bigDecimal = new BigDecimal(value);
            return bigDecimal.compareTo(new BigDecimal("0")) > 0;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public SkuItemVo item(Long skuId) {
        SkuItemVo skuItemVo = new SkuItemVo();

        CompletableFuture<SkuInfoEntity> infoFuture = CompletableFuture.supplyAsync(() -> {
            //1.sku基本信息
            SkuInfoEntity info = getById(skuId);
            skuItemVo.setInfo(info);
            return info;
        }, executor);

        //2.sku图片
        CompletableFuture<Void> imgFuture = CompletableFuture.runAsync(() -> {
            List<SkuImagesEntity> images = imagesService.getImagesBySkuId(skuId);
            skuItemVo.setImages(images);
        }, executor);

        CompletableFuture<Void> saleAttrFuture = infoFuture.thenAcceptAsync((res) -> {
            //3.spu销售属性组合
            List<SkuItemSaleAttrVo> saleAttrVos = skuSaleAttrValueService.getSaleAttrBySpuId(res.getSpuId());
            skuItemVo.setSaleAttr(saleAttrVos);
        }, executor);

        CompletableFuture<Void> descFuture = infoFuture.thenAcceptAsync((res) -> {
            //4.spu介绍
            SpuInfoDescEntity spuInfo = spuInfoDescService.getById(res.getSpuId());
            skuItemVo.setDesp(spuInfo);
        }, executor);

        CompletableFuture<Void> baseAttrFuture = infoFuture.thenAcceptAsync((res) -> {
            //5.spu规格参数信息
            List<SpuItemAttrGroupVo> attrGroups = attrGroupService.getAttrGroupWithAttrsSpuId(res.getSpuId(), res.getCatalogId());
            skuItemVo.setGroupAttrs(attrGroups);
        }, executor);

        CompletableFuture<Void> seckillFuture = CompletableFuture.runAsync(() -> {
            R skuSeckillInfo = seckillFeignService.getSkuSeckillInfo(skuId);
            if (skuSeckillInfo.getCode() == 0) {
                SeckillInfoVo infoVo = skuSeckillInfo.getData(new TypeReference<SeckillInfoVo>() {
                });
                skuItemVo.setSeckillInfoVo(infoVo);
            }
        }, executor);


        try {
            CompletableFuture.allOf(baseAttrFuture, saleAttrFuture, descFuture, imgFuture, seckillFuture).get();
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }

        return skuItemVo;
    }
}